#include "cube.h"

CCube::CCube(void)
{
	std::ifstream f1("cube.dat", std::ios::binary);

	int xs,ys,zs;
	f1 >> xs >> ys >> zs;

	cube = make_shared<CArray3D>(xs,ys,zs);

	char c;

	for(int k=0; k < zs; k++)
		for(int j=ys-1; j >= 0; j--)
			for(int i=0; i < xs; i++)
			{
				f1 >> c;
				(*cube)(i,j,k) = c;
			}
	f1.close();
}

CCube::~CCube(void)
{}

void CCube::Update()
{

}

void CCube::Draw(PArray2D& disp)
{
	// Drawing cube's cross-section, visible layer
	int x0 = ( disp->XSize()-crSection->XSize() )/2;
	int y0 = ( disp->YSize()-crSection->YSize() )/2;

	for(int i=0; i<crSection->XSize(); i++)
		for(int j=0; j<crSection->YSize(); j++)
		{
			if( (*crSection)(i,j)>=128 ) (*disp)(x0+i,y0+j)='o';
			else (*disp)(x0+i,y0+j)=(*crSection)(i,j);
		}
}

void CCube::Rotate(int dir)
{
	PArray3D rotatedCube;

	int xs = cube->XSize();
	int ys = cube->YSize();
	int zs = cube->ZSize();

	switch(dir)
	{
	case ROT_LEFT:
		rotatedCube = make_shared<CArray3D>(zs, ys, xs);
		for(int i=0; i < xs; i++)
			for(int j=0; j < ys; j++)
				for(int k=0; k < zs; k++)
					(*rotatedCube)(zs-k-1, j, i) = (*cube)(i,j,k);
		break;

	case ROT_RIGHT:
		rotatedCube = make_shared<CArray3D>(zs, ys, xs);
		for(int i=0; i < xs; i++)
			for(int j=0; j < ys; j++)
				for(int k=0; k < zs; k++)
					(*rotatedCube)(k, j, xs-i-1) = (*cube)(i,j,k);
		break;

	case ROT_CLKWISE:
		rotatedCube = make_shared<CArray3D>(ys, xs, zs);
		for(int i=0; i < xs; i++)
			for(int j=0; j < ys; j++)
				for(int k=0; k < zs; k++)
					(*rotatedCube)(j, xs-i-1, k) = (*cube)(i,j,k);
		break;

	case ROT_CCLKWISE:
		rotatedCube = make_shared<CArray3D>(ys, xs, zs);
		for(int i=0; i < xs; i++)
			for(int j=0; j < ys; j++)
				for(int k=0; k < zs; k++)
					(*rotatedCube)(ys-j-1, i, k) = (*cube)(i,j,k);
		break;
	}
	cube = rotatedCube;
}

PArray2D CCube::getSurrCells(const PCoords& pos)
{
	int x = pos->X();
	int y = pos->Y();
	int z = pos->Z();
	PArray2D surrCells = make_shared<CArray2D>(3,3);
	for(int i=-1; i<=1; i++)
		for(int j=-1; j<=1; j++)
			(*surrCells)(i,j)=(*cube)(x+i,y+j,z);
	return surrCells;
}

void CCube::setCrossSection(const PCoords& pos)
{
	int xs = cube->XSize();
	int ys = cube->YSize();
	int k = pos->Z();

	crSection = make_shared<CArray2D>(xs,ys);
	for(int i=0; i < xs; i++)
		for(int j=0; j < ys; j++)
		{
			if( (*cube)(i, j, k) == '.')
			{
				if( (*cube)(i, j, k-1) == '.') 	
					(*crSection)(i,j) =' ';
				else
					(*crSection)(i,j) ='.';
			}
			else
				(*crSection)(i,j) = (*cube)(i,j,k);
		}
}
